package cn.rjzjh.tapestry.tams.pages.demo;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.tapestry5.hibernate.annotations.CommitAfter;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.json.JSONObject;
import org.apache.tapestry5.util.TextStreamResponse;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import cn.rjzjh.commons.util.callback.IConvertValue;
import cn.rjzjh.commons.util.callback.impl.ConvertValueDate;
import cn.rjzjh.commons.util.web.EasyUiAssist;
import cn.rjzjh.commons.util.web.OperateResult;
import cn.rjzjh.commons.util.web.PageAssist;
import cn.rjzjh.tapestry.busi.model.Demo;
import cn.rjzjh.tapestry.component.tools.TapestryAssist;
import cn.rjzjh.tapestry.hibernate.services.IHbService;
import cn.rjzjh.tapestry.tams.base.ParentPage;

public class QueryUse extends ParentPage {

	@Inject
	private Session session;

	@Inject
	private IHbService hbService;

	public TextStreamResponse onQuery() {
		JSONObject params = TapestryAssist.packParams(request);
		String userName = TapestryAssist.getParam(params, "userName");
		Criteria criteria = session.createCriteria(Demo.class);
		if (StringUtils.isNotBlank(userName)) {
			criteria.add(Restrictions.eq("userName", userName));
		}
		PageAssist pageAssist = hbService.findByCriteriaPage(criteria);
		Map<String, IConvertValue> convertmap = new HashMap<String, IConvertValue>();
		convertmap.put("birthDay1", new ConvertValueDate());
		String retstr = EasyUiAssist.getJsonForGridAlias(
				pageAssist.getResult(), new String[] { "birthDay,birthDay1" },
				convertmap, pageAssist.getAllNum());
		return TapestryAssist.getTextStreamResponse(retstr);
	}

	@CommitAfter
	public TextStreamResponse onSave() throws Exception {
		Demo demoobj = TapestryAssist.getBeanFromPage(Demo.class, request);
		if (StringUtils.isBlank(demoobj.getId())) {
			demoobj.setId(null);
		}
		session.saveOrUpdate(demoobj);
		return new TextStreamResponse("text/html",
				new OperateResult(1, "修改成功").getJsonMsg(null));
	}

	@CommitAfter
	public TextStreamResponse onDelete() {
		String id = request.getParameter("id");
		hbService.delById(Demo.class, id);
		return retSuccInfo();
	}

}
